﻿using Prism.Regions;
using Prism.Services.Dialogs;
using SmartPlant.Core;
using SmartPlant.Core.Mvvm;
using SmartPlant.Model;
using SmartPlant.Model.DbContext.Biz;
using SmartPlant.Modules.Base.UIEntity;
using SmartPlant.Services.Interfaces;
using SmartPlant.WinCore;
using SmartPlant.WinCore.Helper;
using System.Collections.ObjectModel;
using System.IO;
using System.Windows.Input;
using Telerik.Windows.Controls;
using Unity;

namespace SmartPlant.Modules.Base.ViewModels
{
    public class SpecInputViewModel : RegionViewModelBase
    {
        private readonly ITemplateSettingService _reportService;
        private readonly IImportUtilityService _specInputService;
        public bool TestMode { get; set; }
        public string ProjectID { get; set; }
        public string ProjectName { get; set; }
        private Report report;
        public Report Report
        {
            get
            {
                return this.report;
            }
            set
            {
                this.report = value;
                RaisePropertyChanged();
            }
        }
        public static ObservableCollection<Report> Reports { get; set; } = new ObservableCollection<Report>();

        private ObservableCollection<SpecInputModel> specInputModels = new ObservableCollection<SpecInputModel>();
        public ObservableCollection<SpecInputModel> SpecInputModels
        {
            get
            {
                return this.specInputModels;
            }
            set
            {
                this.specInputModels = value;
                RaisePropertyChanged();
            }
        }
        public ICommand InputCommand { get; set; }
        public ICommand RefreshCommand { get; set; }
        public ICommand DeleteCommand { get; set; }
        public SpecInputViewModel(
            IRegionManager regionManager,
            IDialogService dialog,
            IUnityContainer unityContainer,
            ITemplateSettingService reportService,
            IImportUtilityService specInputService)
           : base(regionManager, unityContainer, dialog)
        {
            _reportService = reportService;
            _specInputService = specInputService;
            this.RefreshCommand = new DelegateCommand(onRefreshCommandExecuted);
            this.InputCommand = new DelegateCommand(onInputCommandExecuted);
            ProjectID = GlobalObject.CurrentProject.ProjId.ToString();
            ProjectName = GlobalObject.CurrentProject.ProjName.ToString();
        }
        protected override void OnInitPage(object obj)
        {
            base.OnInitPage(obj);
            initReports();
        }
        private void onRefreshCommandExecuted(object obj)
        {
            initReports();
        }
        private async void initReports()
        {
            Reports.Clear();
            var list = await _reportService.GetLisAsync(ProjectID, TemplateType.SPEC, -1);//
            list.ForEach(async x =>
            {
                //var XMLs = await _reportService.XMLListAsync(ProjectID, x.InOrOut, x.Type, x.TemplatePath);
                var XMLs = await _reportService.XMLListAsync(ProjectID, x.InOrOut, x.Type, ProjectName);
                x.XMLs.AddRange(XMLs);
            });
            Reports.AddRange(list);
            if (Reports.Count > 0)
            {
                Report = Reports[0];
            }
        }
        /// <summary>
        /// 真实的数据表导入
        /// </summary>
        /// <param name="obj"></param>
        private async void onInputCommandExecuted(object obj)
        {
            try
            {
                var _currentNodes = GlobalObject.CurrentNodes;
                if (_currentNodes == null)
                {
                    Dialog.ShowAltert("导入前必须选择单元号！！！");
                    return;
                }
                if (_currentNodes.Count == 0)
                {
                    Dialog.ShowAltert("导入前必须选择单元号！！！");
                    return;
                }
                if (_currentNodes.Count > 1)
                {
                    Dialog.ShowAltert("数据表导入只能选择一个单元号！！！");
                    return;
                }

                var uploadTasks = new List<Task>();

                foreach (var item in SpecInputModels.Where(x => !string.IsNullOrEmpty(x.FileName) && !string.IsNullOrEmpty(x.InputFilePath)))
                {
                    uploadTasks.Add(Task.Run(async () =>
                    {
                        using var fs = File.OpenRead(item.InputFilePath);
                        byte[] bytes = new byte[fs.Length];
                        await fs.ReadAsync(bytes, 0, (int)fs.Length);
                        var fn = Path.GetFileName(item.InputFilePath);
                        var files = new List<NetworkFileInfo> { new NetworkFileInfo { FileName = fn, Data = bytes } };
                        var filename = Path.GetFileNameWithoutExtension(item.FileName);
                        await _specInputService.UploadSpecTableAsync(ProjectID, filename, ProjectName, _currentNodes[0].Id, files, false, TestMode);
                    }));
                }

                // Wait for all the upload tasks to complete
                await Task.WhenAll(uploadTasks);

                // Show the alert after all uploads are done
                Dialog.ShowAltert("已开始导入作业！！！转入 管理员=》任务作业 查看导入结果");

                //bool result = false;
                //foreach (var item in SpecInputModels.Where(x => !string.IsNullOrEmpty(x.FileName) && !string.IsNullOrEmpty(x.InputFilePath)))
                //{
                //    using var fs = File.OpenRead(item.InputFilePath);
                //    byte[] bytes = new byte[fs.Length];
                //    fs.Read(bytes, 0, (int)fs.Length);
                //    var fn = Path.GetFileName(item.InputFilePath);
                //    var files = new List<NetworkFileInfo> { new NetworkFileInfo { FileName = fn, Data = bytes } };
                //    var filename = Path.GetFileNameWithoutExtension(item.FileName);                    
                //    await Task.Run(async () => await _specInputService.UploadSpecTableAsync(ProjectID, filename, ProjectName,
                //          _currentNodes[0].Id, files, false, TestMode));
                //    //await Task.Run(async () => await _specInputService.UploadSpecTableAsync(ProjectID, filename, report.TemplatePath,
                //    //      _currentNodes[0].Id, files, false, TestMode));
                //    //result = true;
                //}
                ////if (result)
                ////{
                ////    //SpecInputModels.Clear();
                ////    Dialog.ShowAltert("已开始导入作业！！！转入 管理员=》任务作业 查看导入结果");
                ////}
                //Dialog.ShowAltert("已开始导入作业！！！转入 管理员=》任务作业 查看导入结果");
            }
            catch (Exception x)
            {
                string msg = $"导入Excel文件失败：{x.Message}";
                LoggerHelper.Current.Error(msg, x);
            }
        }
    }
}
